package cn.edu.cdu.health.service.impl;

import cn.edu.cdu.health.common.BizException;
import cn.edu.cdu.health.entity.User;
import cn.edu.cdu.health.mapper.UserMapper;
import cn.edu.cdu.health.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public User getById(Integer id) throws BizException {
        return baseMapper.selectById(id);
    }

    @Override
    public User findByUserName(String userName) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", userName);
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public User findByPhone(String phone) {  // 确保有 @Override 注解
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_phone", phone);
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public boolean updateUserInfo(User user) {
        // 1. 校验用户是否存在
        User existingUser = baseMapper.selectById(user.getId());
        if (existingUser == null) {
            return false; // 用户不存在
        }

        // 2. 过滤不允许更新的字段
        user.setCreated(null); // 禁止修改创建时间
        // 注意：如果有其他过滤逻辑，可能误将需要更新的字段设为null

        // 3. 执行更新
        int rows = baseMapper.updateById(user);
        return rows > 0; // 有行数变更才返回true
    }

    @Override
    public User findByPhoneOrEmail(String account) {
        // 关键：用LambdaQueryWrapper，引用实体类字段，触发@TableField映射
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(User::getStatus, 1) // 引用实体类的status字段，自动转换为user_status
                .and(qw -> qw
                        .eq(User::getPhone, account) // 引用实体类phone字段，自动转换为user_phone
                        .or()
                        .eq(User::getEmail, account) // 引用实体类email字段，自动转换为user_email
                );

        return baseMapper.selectOne(queryWrapper);
    }
}